/**
 * 
 */
package org.istt.service.impl;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.istt.dao.TimeHolidayDao;
import org.istt.domain.TimeHoliday;
import org.istt.service.TimeHolidayManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author Huy
 *
 */
@Service("timeHolidayManager")
public class TimeHolidayManagerImpl extends ManagerImpl<TimeHoliday, Long> implements TimeHolidayManager {
	
	/**
	 * @param WorkflowDao the WorkflowDao to set
	 */
	@Autowired
	public void setTimeHolidayDao(TimeHolidayDao dao) {
		this.dao = dao;
	}

	@Override
	public List<Date> getHolidays(Date fromDate, Date toDate) {
		List<Date> result = new ArrayList<Date>();
		List<TimeHoliday> lst = this.dao.findAll();
		if(lst!=null && lst.size()!=0){
			Calendar fDate,tDate,cDate;
			fDate = Calendar.getInstance(); 
			fDate.setTime(fromDate);
//			System.out.println("YEAR 1: "+fDate.get(Calendar.YEAR));
			
			tDate = Calendar.getInstance(); 
			tDate.setTime(toDate);
//			System.out.println("YEAR 2: "+tDate.get(Calendar.YEAR));
			
			int gapOfYear = tDate.get(Calendar.YEAR) - fDate.get(Calendar.YEAR);
			
			cDate = Calendar.getInstance(); 
			for (Iterator<TimeHoliday> iterator = lst.iterator(); iterator.hasNext();) {
				TimeHoliday timeHoliday = (TimeHoliday) iterator.next();
				Date holiday = timeHoliday.getHolidayDate();
				if(timeHoliday.getRepeat()){
					cDate.setTime(holiday);
					
					for (int i = 0; i < gapOfYear; i++) {
						cDate.set(cDate.get(Calendar.YEAR)+gapOfYear, cDate.get(Calendar.MONTH), cDate.get(Calendar.DAY_OF_MONTH));
//						System.out.println("Checking Date: "+cDate.getTime().toString());
						//Do not compare value of YEAR
						if(cDate.after(fDate) && cDate.before(tDate)){
							result.add(cDate.getTime());		
						}
					}
					
				}else{
					if(holiday.after(fromDate) && holiday.before(toDate)) result.add(holiday);
				}
			}
		}
		return result;
	}
	

}
